package com.zonski.jbots.engine.entity;

import com.zonski.jbots.engine.Entity;
import com.zonski.jbots.engine.Modes;
import com.zonski.jbots.engine.Resource;
import com.zonski.jbots.engine.QuickVector;

import java.util.Vector;

/**
 * Designed to have instantaneous turning and moving operations (no inertia)
 */
public class InstantMovementEffect implements MovementEffect
{
    private int maxVelocityMult;
    private int maxVelocityDiv;

    public InstantMovementEffect(int maxVelocity)
    {
        this(maxVelocity, 1);
    }

    public InstantMovementEffect(int maxVelocityMult, int maxVelocityDiv)
    {
        this.maxVelocityMult = maxVelocityMult;
        this.maxVelocityDiv = maxVelocityDiv;
    }

    public void apply(Entity entity)
    {
        MovingEntity me = (MovingEntity)entity;
        boolean canMove = me.isMovable();
        if(entity.getMode() != Modes.DEAD && canMove)
        {
            entity.setEffectiveMode(entity.getMode());
            int targetDirection = me.getTargetDirection();
            int targetVelocity = me.getTargetVelocity();

            int adjustedVelocityMult = this.maxVelocityMult;
            int adjustedVelocityDiv = this.maxVelocityDiv;
            if(entity.getCharge() < entity.getMaxCharge()/2)
            {
                //adjustedVelocityMult *= (entity.getMaxCharge()+entity.getCharge());
                //adjustedVelocityDiv *= (entity.getMaxCharge()*2);
                int ch = entity.getCharge() + entity.getMaxCharge()/2;
                adjustedVelocityMult *= (ch*ch);
                adjustedVelocityDiv *= (entity.getMaxCharge()*entity.getMaxCharge());
            }

            int maxVelocity = adjustedVelocityMult / adjustedVelocityDiv;
            int maxVelocityMod = adjustedVelocityMult % adjustedVelocityDiv;
            if(maxVelocityMod != 0 && entity.getEffectiveModeUpdates()%(adjustedVelocityDiv/maxVelocityMod) == 0)
            {
                maxVelocity ++;
            }
            if(targetVelocity > maxVelocity)
            {
                targetVelocity = maxVelocity;
            }else if(targetVelocity < -maxVelocity){
                targetVelocity = -maxVelocity;
            }

            int turnVelocity = targetDirection - me.direction;
            int xVelocity = Trig.getUnitVelocity(targetVelocity, 
                    targetDirection, Trig.X_INDEX, entity.getEffectiveModeUpdates());
            int yVelocity = Trig.getUnitVelocity(targetVelocity, 
                    targetDirection, Trig.Y_INDEX, entity.getEffectiveModeUpdates());
            me.setVelocity(xVelocity, yVelocity, turnVelocity);
        }else{
            me.setVelocity(0, 0, 0);
            if(entity.getEffectiveMode() == Modes.WALKING)
            {
                me.setEffectiveMode(Modes.NONE);
            }
        }
    }
}
